/*
 *  Copyright 2009 Jamie Gennis <jgennis@gmail.com>.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package com.google.code.gwt.remoteaction.batch.client;

import com.google.gwt.user.client.Timer;
import com.google.inject.Inject;

/**
 * A batching action filter that delays execution of actions for a specified
 * amount of time to allow more actions to be included in the batch.
 * 
 * This class will wait at least as long as the
 * {@link DeferredBatchingActionFilter} before executing the action batch.
 * 
 * @author Jamie Gennis <jgennis@gmail.com>
 */
public class DelayedBatchingActionFilter extends AbstractBatchingActionFilter {

  int delay = 200; // in milliseconds

  /**
   * Construct a new {@code DelayedBatchingActionFilter}.
   */
  @Inject
  public DelayedBatchingActionFilter() {
  }

  /**
   * Construct a new {@code DelayedBatchingActionFilter} with a given action
   * batch execution service.
   * 
   * This constructor is primarily for testing purposes.
   * 
   * @param actionBatchExecutor
   */
  protected DelayedBatchingActionFilter(ActionBatchExecutionServiceAsync actionBatchExecutor) {
    super(actionBatchExecutor);
  }

  @Override
  protected void deferFlush() {
    Timer timer = new Timer() {

      @Override
      public void run() {
        flush();
      }
    };
    timer.schedule(delay);
  }

  /**
   * Get the delay of the deferred action batch flush.
   * 
   * This is the minimum amount of time that will pass from the point when the
   * first action in a batch gets queued up to when the batch gets sent to the
   * server.
   * 
   * @return the delay in milliseconds
   */
  public int getDelay() {
    return delay;
  }

  /**
   * Set the delay of the deferred action batch flush.
   * 
   * @param delay the new delay in milliseconds
   */
  public void setDelay(int delay) {
    this.delay = delay;
  }
}
